import { ref, shallowRef } from 'vue'

import { getHomeData } from './api'
import { catchFn } from '@/libs/common'
import { imagePath } from '@/libs/file-utils'
import { showSigninMask } from './signin-mask/data'
import { luckyDetail, showLuckyMask } from './lucky-mask/data'
import { showGuideQuizMask } from './guide-quiz-mask/data'
import { getQuizResult } from '@/pages/quiz/api'

const mbti = shallowRef<T_MBTIResult>()
const stars = ref(0)
const dailyWords = ref({
  author: '',
  content: '',
  date: '',
})
const luckyList = ref<
  {
    icon: string
    key: T_LuckyType
    value: string
    name: string
    desc: string
  }[]
>([
  {
    icon: imagePath('main/home/lucky-number.png'),
    key: 'luckyNumbers',
    value: '',
    name: '幸运数字',
    desc: '',
  },
  {
    icon: imagePath('main/home/lucky-color.png'),
    key: 'luckyColor',
    value: '',
    name: '穿搭色彩',
    desc: '',
  },
  {
    icon: imagePath('main/home/lucky-food.png'),
    key: 'luckyFood',
    value: '',
    name: '幸运食物',
    desc: '',
  },
  {
    icon: imagePath('main/home/lucky-stone.png'),
    key: 'luckyStone',
    value: '',
    name: '好运晶石',
    desc: '',
  },
  {
    icon: imagePath('main/home/lucky-exercise.png'),
    key: 'suggestExercise',
    value: '',
    name: '推荐运动',
    desc: '',
  },
  {
    icon: imagePath('main/home/lucky-avoid.png'),
    key: 'avoidColor',
    value: '',
    name: '避雷颜色',
    desc: '',
  },
])
const fortuneList = ref<
  {
    icon: string
    key: T_FortuneType
    level: string
    name: string
  }[]
>([
  {
    icon: imagePath('main/home/icon-love.png'),
    key: 'love',
    level: '',
    name: '爱情',
  },
  {
    icon: imagePath('main/home/icon-career.png'),
    key: 'career',
    level: '',
    name: '事业',
  },
  {
    icon: imagePath('main/home/icon-wealth.png'),
    key: 'wealth',
    level: '',
    name: '财富',
  },
  {
    icon: imagePath('main/home/icon-health.png'),
    key: 'health',
    level: '',
    name: '健康',
  },
])

/** 报告倒计时 */
const resultTime = ref(0)

/** 是否显示功能菜单 */
const showHomeMenu = ref(false)

export { mbti, stars, dailyWords, luckyList, fortuneList, resultTime, showHomeMenu }

/**
 * 更新首页数据
 */
const updateData = () =>
  catchFn(async () => {
    const { data } = await getHomeData()

    mbti.value = data.mbtiResult

    // 每日寄语
    const date = new Date()

    dailyWords.value = {
      ...data.dailyWords,
      date: `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`,
    }

    openSignin(data.userInfo.signin)

    const fortune = data.fortuneResult

    if (!fortune) return

    stars.value = fortune.stars

    for (const item of luckyList.value) {
      const val = fortune[item.key]

      item.value =
        typeof val === 'string'
          ? val
          : item.key === 'luckyNumbers'
          ? `（${val.join(',')}）`
          : val.join('\n')
      item.desc = (fortune as any)[item.key + 'Desc'] || item.value || ''
    }

    for (const item of fortuneList.value) {
      item.level = fortune[item.key].level
    }
  })

let timeout: any = null

/**
 * 启动报告倒计时
 */
const startHomeResultTimeout = () => {
  timeout && clearInterval(timeout)

  resultTime.value = 120
  showGuideQuizMask.value = true

  timeout = setInterval(() => {
    resultTime.value--

    if (resultTime.value <= 0) {
      clearInterval(timeout)
      timeout = null
    }

    resultTime.value % 10 === 0 &&
      mbti.value?.typeCode &&
      getQuizResult({ typeCode: mbti.value.typeCode }).then(({ data }) => {
        data.mbtiResult.instructionManual && (resultTime.value = 0)
      })
  }, 1000)
}

/** 提示时间间隔 12h */
const timeLimit = 12 * 60 * 60 * 1000
/** 首次提示 */
let firstOpen = true

/**
 * 关闭签到
 */
const openSignin = (signin: boolean) => {
  if (signin) return

  const lasttime = uni.getStorageSync('signin_tip_time')
  const nowtime = Date.now()

  if (firstOpen || (lasttime && nowtime - Number(lasttime) > timeLimit)) {
    firstOpen = false
    showSigninMask.value = true

    uni.setStorageSync('signin_tip_time', nowtime)
  }
}

const toLuckyDetail = (item: { desc: string; name: string }) => {
  showLuckyMask.value = true
  luckyDetail.value.title = item.name
  luckyDetail.value.info = item.desc
}

export { updateData, startHomeResultTimeout, toLuckyDetail }
